package NIO.channel;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class ChannelTest {
    @Test
    public void test() throws FileNotFoundException {
        System.out.println(ChannelTest.class.getResource(""));
        System.out.println(ChannelTest.class.getResource("/"));
    }
    @Test
    public void write(){
        try {
            //1.得到一个字节输出流通向目标文件
            FileOutputStream outputStream = new FileOutputStream("data.txt");
            //2.得到字节输出流对应的通道
            FileChannel channel = outputStream.getChannel();
            //3.分配缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put("hello,world01".getBytes(StandardCharsets.UTF_8));
            //4.把缓冲区切换为写出模式
            buffer.flip();
            channel.write(buffer);
            channel.close();
            System.out.println("写入数据到文件成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
